﻿using NHibernate;
using AdventureWorks.DataAccess.Utils;
using System;
using AdventureWorks.DataAccess.Repositories;
using AdventureWorks.Domain;
namespace AdventureWorks.DataAccess.Task
{
    public class TaskBase<T> : IDisposable where T : Entity
    {
        private IReporsitoryFactory<T> repositoryFactory;
        private ISessionFactory sessionFactory;

        protected IRepository<T> Repository {get; set;}
        protected ISession Session { get; set; }

        public TaskBase(IReporsitoryFactory<T> repositoryFactory, ISessionFactory sessionFactory)
        {
            this.repositoryFactory = repositoryFactory;
            this.sessionFactory= sessionFactory;
            this.Session = this.sessionFactory.OpenSession();
            this.Repository = this.repositoryFactory.CreateRepository(Session);
        }

        public TaskBase() : this(new RepositoryFactory<T>(), SessionManager.SessionFactory) { }


        #region disposable
        // Dispose() calls Dispose(true)
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing) 
            {
                Session.Close();
                Session.Dispose();
            }
        }

        ~TaskBase() 
        {
            // Finalizer calls Dispose(false)
            Dispose(false);
        }
        #endregion 

    }
}
